package com.mjee.web;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map.Entry;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * Initialize system variables listener. 
 *
 * @author 	<a href="mailto:shixi.zhang@f-club.com">ZhangShixi</a>
 * @version 1.00, 2012-5-7
 */
public class SystemListener implements ServletContextListener {

	/**
	 * System configuration file location 
	 */
	public static final String SYSTEM_CONFIG_LOCATION = "systemConfigLocation";
	/**
	 * Default system configuration file 
	 */
	public static final String DEFAULT_SYSTEM_CONFIG_LOCATION = "/system.properties";
	
	@Override
	public void contextInitialized(ServletContextEvent event) {
		String configLocation = event.getServletContext().
				getInitParameter(SYSTEM_CONFIG_LOCATION);
		if (configLocation == null) {
			configLocation = DEFAULT_SYSTEM_CONFIG_LOCATION;
		}
		
		try {
			initialize(configLocation);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		
	}
	
	/**
	 * Initialize system configuration file.
	 * 
	 * @param configLocation configuration file location.
	 * 
	 * @throws IOException if I/O exception occurs while loading.
	 */
	private void initialize(String configLocation) throws IOException {
		InputStream input = null;
		Properties props = null;
		try {
			input = getClass().getResourceAsStream(configLocation);
			props = new Properties();
			props.load(input);			
		} finally {
			if (input != null) {
				input.close();
			}
		}
		
		for (Entry<Object, Object> entry : props.entrySet()) {
			System.setProperty((String) entry.getKey(), (String) entry.getValue());
		}
	}
	
}
